#    Copyright 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update, COOPGIS_ReportLabStakerReport
import COOPGIS_FormMisc
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings

def BuildBoardDistrictForm(DefaultMap):
    from django.contrib import admin
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([DefaultMap.id, str(DefaultMap.Name)[:30]])
    Maps=Map.objects.all()
    for i in Maps:
        if(not i == DefaultMap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    #Build BoardDistrict Choices List
    BoardDistrictChoices=[]
    BoardDistricts=geography.BoardDistrict.objects.all()
    for i in BoardDistricts:
        BoardDistrictChoices.append([i.id, str(i.Name)[:30]])
    Dict['BoardDistrict']=forms.ChoiceField(BoardDistrictChoices, required=False)
    #BoardDistrict Attribute Fields
    Dict['WKTPolygon']=forms.CharField(widget=forms.TextInput(attrs={'size':'10', 'READONLY':'True'}))
    Dict['Name']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['id']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'2.5', 'READONLY':'True'}))    
    #Action Fields
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)    
    Dict['DeleteIndicator']=forms.BooleanField(required=False)
    return Dict

def ProcessBoardDistrictForm(form, UserName):
    import models
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NewIndicator')
    DeleteIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeleteIndicator')
    Name=COOPGIS_FormMisc.FormGetString(form, 'Name')
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description')
    id = COOPGIS_FormMisc.FormGetInteger(form, 'id', Default=None)
    polygon = COOPGIS_FormMisc.FormGetGeometryFromWKT(form, 'WKTPolygon')
    tempcommand=command.Command()
    try:
        SelectionBoardDistrictid=int(form.data['BoardDistrict'])
        SelectionBoardDistrict=BoardDistrict.objects.filter(id=SelectionBoardDistrictid)[0]
    except:
        SelectionBoardDistrict=None
    if(NewIndicator):
        tempcommand=tempcommand.Create(Name='CreateBoardDistrict', ObjectName=Name, Description=Description, 
                                       Polygon=polygon, CommandUserName=UserName)
        tempcommand.Process()
    elif(UpdateIndicator and id):
        boardDistrict=geography.BoardDistrict.objects.filter(id=id)[0]
        Objectid, ObjectIndexWhenReverseSorted=boardDistrict.GetCommandidData()
        tempcommand=tempcommand.Create(Name='EditBoardDistrict', ObjectName=Name, Description=Description, Polygon=polygon,
                                       Objectid=Objectid, ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted, CommandUserName=UserName)
        tempcommand.Process()
    elif(DeleteIndicator and id):
        boardDistrict=geography.BoardDistrict.objects.filter(id=id)[0]
        if(SelectionBoardDistrict == boardDistrict):
            SelectionBoardDistrict=None
        if(boardDistrict.ResidesOnServerIndicator):
            tempcommand=tempcommand.Create(Name='DeleteBoardDistrict', Objectid=boardDistrict.id, CommandUserName=UserName)
            tempcommand.Process()  
        else:
            boardDistrict.CreateCommand.delete()
            boardDistrict.delete()
    return SelectionBoardDistrict

def PopulateBoardDistrictForm(form, boardDistrict):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False
    form.data['DeleteIndicator']=False
    form.data['WKTPolygon']=''
    if(boardDistrict):
        form.data['Name']=boardDistrict.Name
        form.data['id']=boardDistrict.id
        form.data['Description']=boardDistrict.Description
    return form

